package com.lyu.xiaolvshu.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.lyu.framework.common.exception.BizException;
import com.lyu.framework.common.response.Response;
import com.lyu.xiaolvshu.auth.constant.RedisKeyConstants;
import com.lyu.xiaolvshu.auth.enums.ResponseCodeEnum;
import com.lyu.xiaolvshu.auth.model.vo.verificationcode.SendVerificationCodeReqVO;
import com.lyu.xiaolvshu.auth.service.VerificationCodeService;
import com.lyu.xiaolvshu.auth.sms.AliyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        String phone = sendVerificationCodeReqVO.getPhone();

        String key = RedisKeyConstants.buildVerificationCodeKey(phone);

        if (redisTemplate.hasKey(key)) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }

        String verificationCode = RandomUtil.randomNumbers(6);
        log.info("==> 手机号:{}, 已生成验证码:[{}]", phone, verificationCode);

        // 调用第三方发送短信服务
        threadPoolTaskExecutor.submit(()->{
            aliyunSmsHelper.sendMessage("阿里云短信测试",
                    "18610451988",
                    "SMS_154950909",
                    String.format("{\"code\":\"%s\"}", verificationCode));
        });

        redisTemplate.opsForValue().set(key, verificationCode, 3, TimeUnit.MINUTES);
        return Response.success();
    }
}
